<template>
  <div class="">
    <div class="cardHeader">
      <div class="cardHeader_backBox m_hoverCP">
        <img class="cardHeader_icon m_hoverCP" src="@assets/img/img28.png" alt="" @click="onBack"/>
        <span class="m_hoverCP" @click="onBack">{{$t('message.Return')}}</span>
      </div>
      <div class="cardHeader_numBox_active m_hoverCP" @click="onChangeStep(1)" v-if="step == 1">1</div>
      <div class="cardHeader_numBox_end m_hoverCP" @click="onChangeStep(1)" v-if="step > 1">
        <img class="" src="@assets/img/img45.png" alt=""/></div>
      <div class="cardHeader_textBox m_hoverCP" :class="{'cardHeader_textBox_active':step >= 1}"
           @click="onChangeStep(1)">{{$t('message.Basic_information')}}
      </div>
      <div class="cardHeader_hrBox" :class="{'cardHeader_hrBox_active':step >= 2}"></div>
      <div class="cardHeader_numBox m_hoverCP" @click="onChangeStep(2)" v-if="step < 2">2</div>
      <div class="cardHeader_numBox_active m_hoverCP" @click="onChangeStep(2)" v-if="step == 2">2</div>
      <div class="cardHeader_numBox_end m_hoverCP" @click="onChangeStep(2)" v-if="step > 2">
        <img class="" src="@assets/img/img45.png" alt=""/></div>
      <div class="cardHeader_textBox m_hoverCP" :class="{'cardHeader_textBox_active':step >= 2}"
           @click="onChangeStep(2)">{{$t('message.Build_model')}}
      </div>
      <div class="cardHeader_hrBox" :class="{'cardHeader_hrBox_active':step >= 3}"></div>
      <div class="cardHeader_numBox m_hoverCP" @click="onChangeStep(3,false)" v-if="step < 3">3</div>
      <div class="cardHeader_numBox_active m_hoverCP" @click="onChangeStep(3,false)" v-if="step == 3">3</div>
      <div class="cardHeader_textBox m_hoverCP" :class="{'cardHeader_textBox_active':step == 3}"
           @click="onChangeStep(3,false)">{{$t('message.Carbon_footprint_results')}}
      </div>
    </div>
    <!--  基本信息  -->
    <section class="cardBox" v-show="step == 1">
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item :label="$t('message.Product_name')" required>
                <a-input v-model="queryParam.productName" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="$t('message.Batch_number')" required>
                <a-input v-model="queryParam.batchNumber" ></a-input>
              </a-form-model-item>
            </a-col>      
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item :label="$t('message.Accounting_quantity')" required>
                <a-input-number v-model="queryParam.calculateNumber" @change="onIpitNumbeiPFUlnoiasn" :disabled="disabled" allowClear
                  :placeholder="$t('message.Please_enter')" :step="0.01" :precision="2" :min="0" style="width: 49%">

                </a-input-number>
                <div style="width: 2%;display: inline-block"></div>

                <a-select v-model="queryParam.productUnitId" disabled style="width: 49%">
                  <a-select-opt-group :key="key" :value="key" :label="key" v-for="(value, key, index) in unitData">
                    <a-select-option :key="itemA.id" :value="itemA.id" v-for="(itemA,indexA) in value">
                      {{ itemA.unitCode }}
                    </a-select-option>
                  </a-select-opt-group>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="$t('message.Functional_unit')" required>
                <a-input v-model="queryParam.functionalUnit" ></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item :label="$t('message.Data_cycle')" required>
                <a-range-picker v-model="queryParam.dataRange" :disabled="disabled" @change="onChangeDateRange"
                                style="width: 100%"/>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <a-form-model :model="queryParam" layout="horizontal">
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item :label="$t('message.Life_cycle_boundary')" required>
                <div class="lifeCycleTypeBox">
                  <div class="lifeCycleTypeBox_item"
                       :class="{'lifeCycleTypeBox_item_active':queryParam.lifeCycleType == 1 ,'m_hoverCP':!disabled}"
                       @click="onChangeLifeCycleType(1)">
                    <img class="lifeCycleTypeBox_item_icon" src="@assets/img/img44.png" alt=""/>
                    <div class="lifeCycleTypeBox_item_text1">{{$t('message.From_cradle_to_gate')}}</div>
                    <div class="lifeCycleTypeBox_item_text2">{{$t('message.From_the_acquisition_of_raw_materials_to_the_delivery_of_products')}}</div>
                  </div>
                  <div class="lifeCycleTypeBox_item"
                       :class="{'lifeCycleTypeBox_item_active':queryParam.lifeCycleType == 2,'m_hoverCP':!disabled}"
                       @click="onChangeLifeCycleType(2)">
                    <img class="lifeCycleTypeBox_item_icon" src="@assets/img/img44.png" alt=""/>
                    <div class="lifeCycleTypeBox_item_text1">{{$t('message.From_cradle_to_grave')}}</div>
                    <div class="lifeCycleTypeBox_item_text2">{{$t('message.From_raw_material_acquisition_to_product_abandonment')}}</div>
                  </div>
                  <div class="lifeCycleTypeBox_item"
                       :class="{'lifeCycleTypeBox_item_active':queryParam.lifeCycleType == 3,'m_hoverCP':!disabled}">
                    <img class="lifeCycleTypeBox_item_icon" src="@assets/img/img44.png" alt=""/>
                    <div class="lifeCycleTypeBox_item_text1">{{$t('message.Custom_life_cycle')}}</div>
                    <div class="lifeCycleTypeBox_item_content">
                      <a-checkbox-group v-model="queryParam.cacheLifeCycleItem" :disabled="disabled"
                                        @change="onChangeLifeCycleItem">
                        <a-row :gutter="[0,8]">
                          <a-col :span="8">
                            <a-checkbox value="1">{{$t('message.Raw_material_acquisition')}}</a-checkbox>
                          </a-col>
                          <a-col :span="8">
                            <a-checkbox value="2">{{$t('message.Production_manufacturing')}}</a-checkbox>
                          </a-col>
                          <a-col :span="8">
                            <a-checkbox value="3">{{$t('message.Distribution_and_storage')}}</a-checkbox>
                          </a-col>
                          <a-col :span="8">
                            <a-checkbox value="4">{{$t('message.Product_use')}}</a-checkbox>
                          </a-col>
                          <a-col :span="8">
                            <a-checkbox value="5">{{$t('message.Abandoned_disposal')}}</a-checkbox>
                          </a-col>
                        </a-row>
                      </a-checkbox-group>
                    </div>
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="uploadBox">
          <div class="uploadTitle">{{$t('message.System_boundary_process_flow_chart')}}</div>
          <div class="uploadContent">
            <!--  :text="$t('message.Upload')" -->
            <j-image-upload class="avatar-uploader" v-model="queryParam.flowChart" :disabled="disabled"
                            isMultiple :number="3"></j-image-upload>
          </div>
          <div class="uploadTip">{{$t('message.Upload_up_to_3_photos')}}</div>
        </div>
      </div>
      <div class="optionBox">
        <div class="optionItem_save m_hoverCP" @click="onSave1()"> {{$t('message.Save')}}</div>
        <div class="optionItem_next m_hoverCP" @click="onSave1('next')"> {{$t('message.Next_life_cycle_model_build')}}</div>
      </div>
    </section>
    <!--  搭建模型  -->
    <section class="topsw" v-show="step == 2">
      <carbonFootprintModelBuild ref="carbonFootprintModelBuild" :queryParam="queryParam" @changeStep="onChangeStep"
                                 @back="onBack"/>
    </section>
    <!--  碳足迹结果  -->
    <section v-show="step == 3">
      <a-spin :spinning="spinning">
        <carbonFootprintResults ref="carbonFootprintResults" :queryParam="queryParam"
                                :generateResultData="generateResultData" @archive="onChangeArchive"
                                @changeStep="onChangeStep"/>
      </a-spin>
    </section>
  </div>
</template>

<script>
import {getAction, postAction} from "@api/manage";
import {cloneObject} from '@/utils/util'
import carbonFootprintModelBuild
  from '@views/module_footprint/footprintProductView/modules/carbonFootprintModelBuild/carbonFootprintModelBuild.vue'
import carbonFootprintResults from '@views/module_footprint/footprintProductView/modules/carbonFootprintResults.vue'

export default {
  name: 'footprintProductForm',
  components: {
    carbonFootprintModelBuild,
    carbonFootprintResults,
  },
  data() {
    return {
      step: 1, /* 1基本信息 2搭建模型 3碳足迹结果 */
      queryParam: {}, /* 表单数据 */
      unitData: [], /* 单位 */
      generateResultData: {}, /* 产品碳足迹-碳足迹结果 */
      spinning: false,
    }
  },
  computed: {
    disabled() {
      if (this.queryParam.calculateArchived === '1') {
        return true
      } else {
        return false
      }
    }
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    onIpitNumbeiPFUlnoiasn(){
      this.queryParam.functionalUnit=this.queryParam.calculateNumber+this.queryParam.productUnitName+this.queryParam.productName
    },
    /**
     * 核算归档
     */
    onChangeArchive() {
      this.queryParam.calculateArchived = '1'
      this.onChangeStep(3, true)
    },
    /**
     * 切换第几步
     * @param step 1基本信息 2搭建模型 3碳足迹结果
     */
    onChangeStep(step, isFinish) {
      console.log('onChangeStep', step)
      if (step == 1) {
        // 产品碳足迹-基本信息
        this.step = step
      }
      if (step == 2) {
        // 产品碳足迹-搭建模型
        if (!this.queryParam.id) {
          this.$message.warn(this.$t('message.Please_save_the_basic_information_before_viewing'))
          return
        }
        this.step = step
        this.$nextTick(() => {
          this.$refs.carbonFootprintModelBuild.getData()
        })
      }
      if (step == 3) {
        // 产品碳足迹-碳足迹结果
        if (!this.queryParam.id) {
          this.$message.warn(this.$t('message.Please_save_the_basic_information_before_viewing'))
          return
        }
        this.spinning = true
        getAction('/footprintProduct/cyFootprintProduct/generateResult', {
          calculateId: this.queryParam.id,
          isFinish: isFinish
        }).then((res) => {
          if (res.success) {
            let resData = res.result || {}
            let cptzjValue = 0 // 总碳排
            let activeCollapseKey = [] // 默认展开第一层折叠面板
            if (resData.detailList && resData.detailList.length > 0) {
              resData.detailList.forEach((item, index) => {
                cptzjValue = cptzjValue + item.total
                activeCollapseKey.push(String(index))
                let activeCollapseKey2 = []  // 默认展开第二层折叠面板
                if (item.childList && item.childList.length > 0) {
                  item.childList.forEach((item2, index2) => {
                    if (item2.total > 0) {
                      activeCollapseKey2.push(String(index2))
                    }
                  })
                }
                item.activeCollapseKey = activeCollapseKey2
              })
              resData.cptzjValue = cptzjValue
              resData.detailList.forEach(item => {
                item.proportion = Number(((item.total / resData.cptzjValue) * 100).toFixed(2))
              })
            }
            resData.cptzjValue = cptzjValue
            this.generateResultData = resData
            this.step = step
            this.$nextTick(() => {
              console.log('carbonFootprintResults', this.$refs.carbonFootprintResults, resData)
              this.$set(this.$refs.carbonFootprintResults, 'activeCollapseKey', activeCollapseKey)
              this.$refs.carbonFootprintResults.drawCharts(this.generateResultData)
            })
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.spinning = false
        })
      }
    },
    getData() {
      console.log('getData', this.queryParam)
      // 单位
      getAction('/emission/factor/cyEmissionUnit/getAllUnitByGroup').then((res) => {
        if (res.success) {
          this.unitData = res.result || {}
          console.log('getData111', this.unitData)
        }
      });
    /*  getAction('/sys/category/loadTreeRoot', {
        pcode: 'A03',
        async: false,
      }).then((res) => {
        if (res.success) {
          this.unitData = res.result || []
        }
      });*/
    },
    // ============================================================== 第一步，基本信息
    /**
     * 基本信息-选择数据周期
     */
    onChangeDateRange(date, dateString) {
      console.log('onChangeDateRange', date, dateString)
      if (dateString[0]) {
        this.queryParam.beginTime = dateString[0] + ' 00:00:00'
        this.queryParam.endTime = dateString[1] + ' 23:59:59'
      } else {
        this.queryParam.beginTime = dateString[0]
        this.queryParam.endTime = dateString[1]
      }
    },
    /**
     * 基本信息-生命周期边界
     * @param e
     */
    onChangeLifeCycleItem(e) {
      console.log('onChangeLifeCycleItem', e);
      this.$set(this.queryParam, 'lifeCycleType', 3)
    },
    /**
     * 基本信息-生命周期边界
     * @param e
     */
    onChangeLifeCycleType(e) {
      console.log('onChangeLifeCycleType', e);
      this.$set(this.queryParam, 'lifeCycleType', e)
      this.$set(this.queryParam, 'cacheLifeCycleItem', undefined)
    },
    /**
     * 基本信息-检查表单数据
     */
    checkFormData1() {
      if (!this.queryParam.calculateNumber && this.queryParam.calculateNumber !== 0 && this.queryParam.calculateNumber !== '0') {
        this.$message.warn(this.$t('message.please_enter_accounting_quantity'))
        return false
      }
      if (!this.queryParam.beginTime || !this.queryParam.endTime) {
        this.$message.warn(this.$t('message.please_select_data_period'))
        return false
      }
      if (!this.queryParam.lifeCycleType) {
        this.$message.warn(this.$t('message.please_select_life_cycle_boundary'))
        return false
      }
      if (this.queryParam.lifeCycleType == 3 && (!this.queryParam.cacheLifeCycleItem || this.queryParam.cacheLifeCycleItem && this.queryParam.cacheLifeCycleItem.length == 0)) {
        this.$message.warn(this.$t('message.Please_select_at_least_one_custom_life_cycle'))
        return false
      }
      return true
    },
    /**
     * 基本信息-保存
     */
    onSave1(next) {
      console.log('onSave1',this.queryParam)
      if (this.checkFormData1()) {
        let reqData = cloneObject(this.queryParam)
        if (reqData.lifeCycleType == 1) {
          // 从摇篮到大门
          reqData.lifeCycleItem = '1,2,3'
        } else if (reqData.lifeCycleType == 2) {
          // 从摇篮到坟墓
          reqData.lifeCycleItem = '1,2,3,4,5'
        } else if (reqData.lifeCycleType == 3) {
          // 自定义
          reqData.cacheLifeCycleItem.forEach(item => {
            item = Number(item)
          })
          reqData.cacheLifeCycleItem = reqData.cacheLifeCycleItem.sort((a, b) => {
            return a - b
          })
          reqData.lifeCycleItem = reqData.cacheLifeCycleItem.join(',')
        }
        reqData.calculateStatus = !next ? 1 : 2
        postAction('/footprintProduct/cyFootprintProduct/saveCalculate', reqData).then((res) => {
          if (res.success) {
            this.$message.success('保存基本信息成功')
            this.queryParam.id = res.result.id
            if (next) {
              this.onChangeStep(2)
            } else {
              this.onBack()
            }
          }else{
            this.$message.error(res.message)
            
          }
        });
      }
    },
    // ============================================================== 第二步，搭建模型

    // ============================================================== 第三步，碳足迹结果

    // ============================================================== 其他

    // ==============================================================================
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 返回
     */
    onBack() {
      this.$emit('back')
    },
  },
};

</script>

<style lang="less" scoped>
.topsw{
  padding: 24px ;
  background: #FFFFFF;
  margin-top: 24px;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-form-item {
  margin-bottom: 44px;
}

/deep/ .ant-form-item {
  margin-bottom: 44px;
}

.cardHeader {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  width: 100%;
  height: 64px;
  background: #FFFFFF;

  .cardHeader_backBox {
    position: absolute;
    top: 50%;
    left: 24px;
    transform: translateY(-50%);
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
  }

  .cardHeader_icon {
    width: 16px;
    height: 16px;
  }


  .cardHeader_numBox {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.4);
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.4);
  }

  .cardHeader_numBox_active {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #148958;
    border: 1px solid #148958;
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: rgba(255, 255, 255, 0.9);
  }


  .cardHeader_numBox_end {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border: 1px solid #148958;

    img {
      width: 16px;
      height: 16px;
    }
  }

  .cardHeader_textBox {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.4);
  }

  .cardHeader_textBox_active {
    color: #148958;
  }

  .cardHeader_hrBox {
    width: 344px;
    height: 2px;
    background: #DCDCDC;
  }

  .cardHeader_hrBox_active {
    background: #148958;
  }


}

.cardBox {
  margin: 24px auto 0;
  width: 1400px;
  overflow: hidden;
  padding: 20px 64px;
  background: #FFFFFF;
  border-radius: 3px;
}


.cardBox2 {
  margin: 24px 300px auto;
  overflow: hidden;
  padding: 24px;
  background: #FFFFFF;
  border-radius: 3px;
}

.cardBox2_title {
  font-family: PingFang SC, PingFang SC;
  font-weight: bold;
  font-size: 16px;
  color: #333333;
}


.lifeCycleTypeBox {
  display: flex;
  justify-content: space-between;
  gap: 30px;

  .lifeCycleTypeBox_item {
    position: relative;
    flex: 1;
    box-sizing: border-box;
    padding: 24px;
    height: 132px;
    background: #FFFFFF;
    border-radius: 3px;
    border: 1px solid #DCDCDC;

    .lifeCycleTypeBox_item_icon {
      display: none;
    }

    .lifeCycleTypeBox_item_text1 {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 16px;
      color: #333333;
      line-height: 22px;
    }

    .lifeCycleTypeBox_item_text2 {
      margin-top: 12px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #888888;
      line-height: 22px;
    }

    .lifeCycleTypeBox_item_content {
      margin-top: 12px;
    }
  }

  .lifeCycleTypeBox_item_active {
    position: relative;
    background: #F7FDF8;
    border: 1px solid #148958;

    .lifeCycleTypeBox_item_icon {
      display: block;
      position: absolute;
      top: 0;
      right: 0;
      width: 45px;
      height: 39.5px;
    }

    .lifeCycleTypeBox_item_text1 {
      color: #148958;
    }

    .lifeCycleTypeBox_item_text2 {
    }

    .lifeCycleTypeBox_item_content {
      margin-top: 12px;
    }
  }
}

.uploadBox {
  .uploadTitle {
    color: rgba(0, 0, 0, 0.85);
  }

  .uploadContent {
    margin-top: 11px;
  }

  .uploadTip {
    margin-top: 8px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.4);
  }
}


.optionBox {
  margin-top: 130px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;

  .optionItem {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 103px;
    height: 32px;
    border-radius: 3px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
  }

  .optionItem_cancel {
    background: #E7E7E7;
    color: rgba(0, 0, 0, 0.9);
  }

  .optionItem_confirm {
    background: #148958;
    color: rgba(255, 255, 255, 0.9);
  }

  .optionItem_save {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 55px;
    height: 32px;
    background: #FFFFFF;
    border-radius: 3px;
    border: 1px solid #148958;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #148958;
  }

  .optionItem_next {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 16px;
    height: 32px;
    background: #148958;
    border-radius: 3px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.9);
  }
}
</style>
